package A013executor;

import java.util.concurrent.*;

public class A008_关闭线程池_isTerminatedShutdown {

    public static void doSomething(ExecutorService executorService, int numOfRequest) {

        System.out.println(((ThreadPoolExecutor) executorService).getRejectedExecutionHandler().getClass() + ":");

        for (int i = 1; i <= numOfRequest; i++) {
            final int tempInt = i;

            try {
                executorService.execute(() -> {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t 给用户:" + tempInt + " 办理业务");
                });
            } catch (Exception e) {
                System.err.println("序号=" + tempInt + "\t" + ((ThreadPoolExecutor) executorService).getRejectedExecutionHandler().getClass() + "\t" + e);
            }
        }
    }

    public static ExecutorService newMyThreadPoolExecutor(int corePoolSize,
                                                          int maximumPoolSize, int blockingQueueSize, RejectedExecutionHandler handler) {
        return new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                5,//keepAliveTime
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(blockingQueueSize),
                Executors.defaultThreadFactory(),
                handler);
    }


    public static void main(String[] args) throws InterruptedException {
//        ExecutorService executorService = newMyThreadPoolExecutor(2, 5, 3, new ThreadPoolExecutor.AbortPolicy());
//        doSomething(executorService, 20);
//        TimeUnit.SECONDS.sleep(5);
//        System.out.println("\n\n");

//        ExecutorService executorService = newMyThreadPoolExecutor(2, 5, 3, new ThreadPoolExecutor.CallerRunsPolicy());
//        doSomething(executorService, 20);
//        TimeUnit.SECONDS.sleep(5);
//        System.out.println("\n\n");

//        ExecutorService executorService = newMyThreadPoolExecutor(2, 5, 3, new ThreadPoolExecutor.DiscardOldestPolicy());
//        doSomething(executorService, 20);
//        TimeUnit.SECONDS.sleep(5);
//        System.out.println("\n\n");

        ExecutorService executorService = newMyThreadPoolExecutor(2, 5, 3, new ThreadPoolExecutor.DiscardPolicy());
        doSomething(executorService, 20);

        executorService.shutdown();
        while(!executorService.isTerminated()){
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println("executorService.isTerminated()=" + executorService.isTerminated() + "\texecutorService.getActiveCount()=" + ((ThreadPoolExecutor) executorService).getActiveCount());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("关闭线程池");
    }

}
